from flask import Blueprint, jsonify, request, session, render_template
from config import db
from models.models import User

userinfo = Blueprint('userinfo', __name__)


@userinfo.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


# 获取所有用户信息
@userinfo.route("/test/users")
def get_users():
    page = int(request.args.get("curr", 1))  # 当前页码，默认为1
    per_page = int(request.args.get("nums", 10))  # 每页记录数，默认为10
    users = users = User.query.paginate(page=page, per_page=per_page)
    data = []
    for user in users:
        user_info = {
            'id': user.id,
            'username': user.username,
            'sex': user.sex,
            'address': user.address,
            'email': user.email
        }
        data.append(user_info)
    return jsonify({'code': 0, 'count': users.total, 'msg': '', 'data': data})


@userinfo.route("/api/user")
def get_user_info():
    user_id = session.get('user_id')
    user = User.query.filter_by(id=user_id).first()
    if user:
        user_info = {
            "name": user.name,
            "sex": user.sex,
            'address': user.address,
            'email': user.email,
            'phone': user.phone,
            "birthdate": user.birthdate
        }
        return jsonify(user_info)
    else:
        return jsonify({"error": "没有找到用户！"}), 404


@userinfo.route('/update/userinfo', methods=['POST', "GET"])
def submit_form():
    if request.method == 'POST':
        user_id = session.get('user_id')
        user = User.query.get(user_id)
        if user:
            user.name = request.form.get('name')
            user.sex = request.form.get('sex')
            user.address = request.form.get('address')
            user.email = request.form.get('email'),
            user.phone = request.form.get('phone'),
            user.birthdate = request.form.get('birthdate')
            db.session.commit()
            return jsonify({"message": "用户信息更新成功！"})
        else:
            return jsonify({"message": "没有找到用户"})
    return render_template('update_userinfo.html')


@userinfo.route('/user/manage')
def user_manage():
    return render_template('personal_center.html')


@userinfo.route('/user/info')
def user_info():
    return render_template('user_info.html')



@userinfo.route('/add/2')
def add2():
    pass
